<script setup lang="ts">
import { ref } from 'vue'
import { showLoadingToast } from 'vant'
import base64ToBlob from 'b64-to-blob'
import { request } from '../utils/http.ts'
import { showToast } from 'vant'

const avatar = ref(new URL('../assets/avatar.png', import.meta.url).href)
// const showToast = (message: string) => Toast(message);
const Nickname = ref('')
const Gender = ref('')
const Content = ref('')
const Birthday = ref('')

const GenderColumns = [
  { text: '男', value: '1' },
  { text: '女', value: '0' }
]

let showBirthday = ref(false)

let showAvatar = ref(false)

let showGender = ref(false)

const selectBirthday = ref(['2021', '01', '01'])

const onGenderConfirm = (res: any) => {
  Gender.value = res.selectedValues.join(',') == 1 ? '男' : '女'
  showGender.value = false
}
const onGenderCancel = () => {
  showGender.value = false
}

const actions = [{ name: '拍照' }, { name: '本地选择' }]

const onSubmitContent = () => {
  showRight.value = false
}

const onSumbitName = () => {
  console.log('1111')

  showName.value = false
}

const minDate = new Date(1924, 1, 1)
const maxDate = new Date(3000, 5, 1)

// const onCancel = () => showToast("取消");
// 拍照/本地选择
const selectAvatar = async (item: { name: string; }) => {
  if (showAvatar.value) {
    // 拍照
    if (item.name === '拍照') {
      const data = await headlines.pickerCamera()
      await onUpdateAvatar(data)
    } else {
      // 相册上传
      const data = await headlines.pickerPhoto()
      await onUpdateAvatar(data)
    }
  }
}

// 1.3 头像上传
const onUpdateAvatar = async (data: string) => {
  try {
    showAvatar.value = false
    showLoadingToast({ message: '正在上传', duration: 0, forbidClick: true })
    const image = base64ToBlob(data, 'image/jpeg')
    const fd = new FormData()
    fd.append('file', image, Date.now() + '.jpeg')
    const res = await request.post<headlinesResponse<{ photo: string }>>('user/photo', fd)
    const datas = JSON.parse(JSON.stringify(res.data))
    avatar.value = datas.photo

    // 修改原生侧的头像 ProfileInfo
    const user = headlines.getUserInfo()
    user.photo = datas.photo
    headlines.updateUserInfo(user)
  } catch (err) {
    showToast({ message: '上传失败' })
  }
}

let showRight = ref(false)
let showName = ref(false)

const selectGender = ref(1)

// 设置默认值
let res: ProfileInfo = await headlines.getUserInfo()
  avatar.value = res.photo
  Nickname.value = res.name
  Gender.value = res.gender == '1' ? '男' : '女'
  Content.value = res.intro || ''
  Birthday.value = res.birthday
  selectBirthday.value = Birthday.value.split('-')
  selectGender.value = Number(res.gender)

// .then(res => {
//   // showToast(JSON.stringify(res));
//   avatar.value = res.photo
//   Nickname.value = res.name
//   Gender.value = res.gender == 1 ? '男' : '女'
//   Content.value = res.intro
//   Birthday.value = res.birthday
//   selectBirthday.value = Birthday.value.split('-')
//   selectGender.value = res.gender
// })

const onChangeBirthday = (data: { selectedValues: any[] }) => {
  Birthday.value = data.selectedValues.join('-')
  showBirthday.value = false
}

const onBack = () => {
  headlines.back()
}

// 更新用户数据
const updateUserInfo = async () => {
  await headlines.updateUserInfo({
    name: Nickname.value,
    gender: Gender.value,
    birthday: Birthday.value,
    real_name: '',
    intro: Content.value,
    photo: avatar.value
  } as IUserUpdate)
}

// 退出登录
const onLogout = () => {
  headlines.logout()
}
</script>

<template>
  <div class="profile-edit-page">
    <van-nav-bar title="个人信息" left-arrow @click-left="onBack" />
    <van-cell-group>
      <div class="avatar" @click="showAvatar = true">
        <van-field label="头像" readonly></van-field>

        <img :src="avatar" style="width: 30px" />

        <img src="../assets/ic_public_arrow_right_filled.png" />
      </div>

      <van-cell title="昵称" is-link v-model:value="Nickname" readonly @click="showName = true"></van-cell>

      <van-cell title="简介" is-link v-model:value="Content" readonly @click="showRight = true"></van-cell>
    </van-cell-group>

    <div style="width: 100%; height: 24px; background-color: #f7f8fa"></div>

    <van-cell-group>
      <van-cell title="性别" readonly v-model:value="Gender" is-link @click="showGender = true"></van-cell>
      <van-cell
        title="生日"
        readonly
        is-link
        v-model:value="Birthday"
        placeholder="请选择日期"
        @click="showBirthday = true"
      ></van-cell>
    </van-cell-group>

    <div class="save">
      <van-button block color="linear-gradient(to right, #fc6528, #fd4f4e)" type="primary" @click="updateUserInfo"">
        保存
      </van-button>
    </div>

    <div class="login-out">
      <van-button block color="linear-gradient(to right, #fc6528, #fd4f4e)" type="primary" @click="onLogout">
        退出登录
      </van-button>
    </div>
  </div>
  <!-- 底部弹出层 -->
  <!-- 修改生日的弹层 -->
  <van-popup v-model:show="showBirthday" position="bottom" :round="true">
    <!-- <div>123</div> -->
    <van-date-picker
      title="生日"
      v-model="selectBirthday"
      @cancel="showBirthday = false"
      @confirm="onChangeBirthday"
      :min-date="minDate"
      :max-date="maxDate"
    />
  </van-popup>
  <van-action-sheet
    v-model:show="showAvatar"
    :actions="actions"
    cancel-text="取消"
    close-on-click-action
    @select="selectAvatar"
  />

  <van-popup v-model:show="showGender" position="bottom" :style="{ height: '40%' }">
    <van-picker title="性别" :columns="GenderColumns" @confirm="onGenderConfirm" @cancel="onGenderCancel" />
  </van-popup>

  <van-popup v-if="showRight" v-model:show="showRight" position="right" :style="{ width: '100%', height: '100%' }">
    <van-nav-bar
      title="简介"
      left-arrow
      @click-left="showRight = false"
      @click-right="onSubmitContent"
      right-text="提交"
    />
    <van-cell-group inset>
      <van-field
        v-model="Content"
        rows="2"
        autosize
        type="textarea"
        placeholder="请输入简介"
        style="background-color: #f7f8fa"
        max-Length="100"
        show-word-limit
      />
    </van-cell-group>
  </van-popup>
  <van-popup v-if="showName" v-model:show="showName" position="right" :style="{ width: '100%', height: '100%' }">
    <van-nav-bar
      title="编辑昵称"
      left-arrow
      @click-left="showName = false"
      right-text="提交"
      @click-right="onSumbitName"
    />
    <van-field
      v-model="Nickname"
      rows="1"
      autosize
      type="textarea"
      placeholder="请输入昵称"
      style="background-color: #f7f8fa"
    />
  </van-popup>
</template>

<style lang="css" scoped>
.avatar {
  display: flex;
  align-items: center;
}

.profile-edit-page {
  padding: 10px;
}

.login-out {
  margin-top: 20px;
  flex: 1;
}

.save {
  margin-top: 20px;
  flex: 1;
}
</style>

